package com.kx.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    private static ThreadLocal<SqlSession> sessionThreadLocal = new ThreadLocal<>();

   static  {
        try {
            InputStream in = Resources.getResourceAsStream("Mybatis.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private static SqlSession getSession() {
        SqlSession sqlSession = sqlSessionFactory.openSession(false);
        sessionThreadLocal.set(sqlSession);
        return sqlSession;
    }


    public static <T> T getMapper(Class<T> tClass) {
        SqlSession sqlSession = getSession();
        return sqlSession.getMapper(tClass);
    }


    public static void commit() {
        SqlSession sqlSession = sessionThreadLocal.get();
        if (sqlSession != null) {
            sqlSession.commit();
//            sessionThreadLocal.remove();
//            sqlSession.close();
            close();
        }
    }

    public static void rollback() {
        SqlSession sqlSession = sessionThreadLocal.get();
        if (sqlSession != null) {
            sqlSession.rollback();
//            sessionThreadLocal.remove();
//            sqlSession.close();
            close();
        }
    }


    private static void close() {
        SqlSession sqlSession = sessionThreadLocal.get();
        if (sqlSession != null) {
            sessionThreadLocal.remove(); //一定要remove,否则会导致内存泄漏
            sqlSession.close();
        }
    }
}
